package com.huonan.utils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Supplier;

@Slf4j
public class RetryUtil {

    private static RetryUtil instance;

    private RetryUtil() {
        // 私有构造函数，防止外部实例化
    }

    public static RetryUtil getInstance() {
        if (instance == null) {
            instance = new RetryUtil();
        }
        return instance;
    }

    @SneakyThrows
    public <T> T retry(Supplier<T> supplier, int maxRetries, long delayMillis) {
        int retry = 0;
        while (retry < maxRetries) {
            if (retry>1) {
                log.warn("重试中,第[{}]次",retry);
            }
            try {
                return supplier.get();
            } catch (Exception e) {
                retry++;
                if (retry == maxRetries) {
                    throw e; // 如果重试次数达到限制，则抛出异常
                }
                Thread.sleep(delayMillis); // 等待一段时间后重试
            }
        }
        log.info("重试[{}]次，失败", maxRetries);
        return null; // 达到重试次数限制，返回空值
    }

}